package com.sax.parsers;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class JoinSeparatedPosListCharacters extends DefaultHandler
{
	private boolean mInPosList;
	private String NEWLINE = System.getProperty("line.separator");
	private StringBuilder mPosListStringBuilder = new StringBuilder();
	private final PrintWriter mOut = new PrintWriter(
			new BufferedWriter(
					new OutputStreamWriter(
							System.out,
							StandardCharsets.UTF_8)),
				true)   ;
	
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
		this.mOut.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		this.mInPosList = false;
	}
	
	public void startElement(
	  String namespaceURI,
	  String localName, // simple name
	  String qName, // qualified name
	  Attributes attrs) throws SAXException {
	  	
	  	if(qName.equalsIgnoreCase("gml:posList"))
	  	{
	  		this.mInPosList = true;
	  		this.mPosListStringBuilder.setLength(0);
	  	}
	  	
	  	this.mOut.printf("<%s", qName);
	  	
	  	for(int i = 0; i < attrs.getLength(); i++) {
			this.mOut.printf(" %s = \"%s\"", attrs.getQName(i), attrs.getValue(i));
		}
	  	
	  	this.mOut.print(">");
	  	//System.out.println();
	}

	public void endElement(String uri, String localName, String qName)
	{
		if(this.mInPosList && qName.equalsIgnoreCase("gml:posList"))
		{
			this.mInPosList = false;
			this.mOut.print(this.mPosListStringBuilder.toString());
		}
		
		this.mOut.printf("</%s>", qName);
		//System.out.println();
	}

	public void characters(char buf[], int offset, int len) throws SAXException
	{
		String text = new String(buf, offset, len);
		
		if(this.mInPosList)
		{
			//System.err.printf("loaded characters: %s", text);
			//if(text.contains(NEWLINE))
				//System.err.print("contains new line");
			//System.err.print("ENDLOAD");
			this.mPosListStringBuilder.append(text.replaceAll("\\r|\\n", ""));
		}
		else
		{
			this.mOut.print(text);
		}
	}
	
	@Override
	protected void finalize() throws Throwable {
		// TODO Auto-generated method stub
		super.finalize();
	}
  }
